package com.zyd.blog.homeart.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.zyd.blog.homeart.service.IFineArtService;
import com.zyd.blog.homeart.util.TimeUtil;
import com.zyd.blog.persistence.beans.*;
import com.zyd.blog.persistence.mapper.*;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liusongqi
 * @since 2020-03-05
 */
@Service
public class FineArtServiceImpl implements IFineArtService {
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private FineArtMapper fineArtMapper;
    @Autowired
    private DictionariesMapper dictionariesMapper;
    @Autowired
    private MyParticipateMapper myParticipateMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CenterMapper centerMapper;
    @Autowired
    private CommentRelationMapper commentRelationMapper;
    @Autowired
    private TimeUtil timeUtil;
    @Autowired
    private SoftProductMapper softProductMapper;

    @Autowired
    private DesignArticleMapper designArticleMapper;
    @Override
    public Integer insertFineArt(String fineTitle, String fineContent, String draft, String fineImage, String list,String userId) {
        List<Product> products = JSONArray.parseArray(list, Product.class);
        List<String> list1 = new ArrayList<>();
        for (int i = 0; i < products.size(); i++) {
            Product product = new Product();
            String uuid = UuidUtils.getUUID();
            product.setProductId(uuid);
            product.setImageId(products.get(i).getImageId());
            product.setProductContent(products.get(i).getProductContent());
            product.setShopContent(products.get(i).getShopContent());
            product.setShopImage(products.get(i).getShopImage());
            product.setShopPrice(products.get(i).getShopPrice());
            product.setShopLink(products.get(i).getShopLink());
            list1.add(uuid);
            productMapper.insert(product);
        }
        FineArt fineArt = new FineArt();
        fineArt.setAddTime(sdf.format(System.currentTimeMillis()));
        fineArt.setFineId(UuidUtils.getUUID());
        fineArt.setFineImage(fineImage);
        fineArt.setProductId(StringUtils.join(list1, ","));
        fineArt.setZanNumber(0);
        fineArt.setDiscussNumber(0);
        fineArt.setCollectionNumber(0);
        fineArt.setFineContent(fineContent);
        fineArt.setExamine("0");
        fineArt.setNow("1");
        fineArt.setDraft(draft);
        fineArt.setFineTitle(fineTitle);
        fineArt.setTop("1");
        fineArt.setCategory("0");
        fineArt.setUserId(userId);
        fineArt.setDeleteState("1");
        fineArt.setUserName("用户名");
        fineArt.setNum(0);
        fineArt.setUseState("0");
        fineArt.setUserImage("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2932779449,831692746&fm=26&gp=0.jpg");
        fineArt.setTopTime(sdf.format(System.currentTimeMillis()));
        int insert = fineArtMapper.insert(fineArt);
        return insert;
    }

    @Override
    public Map<String,Object> soft(String userId,int page,int count) {
        FineArt fineArt = new FineArt();
        fineArt.setTop("0");
        int i = fineArtMapper.selectCount(fineArt);
        List<FineArtNew> soft=fineArtMapper.soft(userId,count*page-count,count);
        Map<String,Object> map = new HashMap<>();
        map.put("list",soft);
        int i1 = fineArtMapper.selectCount(null);
        if (page * count <= i1) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }

    @Override
    public Map<String, Object> personalSoft(String userId, int page, int count) {
        List<FineArtNew> soft=fineArtMapper.personalSoft(userId,count*page-count,count);
        Map<String,Object> map = new HashMap<>();
        map.put("list",soft);
        int i1 = fineArtMapper.selectCount(null);
        if (page * count <= i1) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }

    @Override
    public Map<String, Object> searchDesign(String value, String userId, int page, int count) {
        int i = fineArtMapper.searchCount(value);
        List<FineArtNew> soft = fineArtMapper.searchDesign(value,userId, count * page - count, count );
        Map<String, Object> map = new HashMap<>();
        map.put("list", soft);
        int i1 = fineArtMapper.searchCountAll(value);
        //hasmore 1有下一页   0 没有 判断页数和条数  相乘 是否小于 总条数 以此判断 是否有下一页
        if (page * count <= i1) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }

    @Override
    public Map<String, Object> personalSoftOrder(String userId, int page, int count,String coverUserId) {
        List<FineArtNew> soft=fineArtMapper.personalSoftOrder(userId,count*page-count,count,coverUserId);
        Map<String,Object> map = new HashMap<>();
        map.put("list",soft);
        int i1 = fineArtMapper.selectCount(null);
        if (page * count <= i1) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }


    @Override
    public Integer fabulous(String id, String userId, String category, String state) throws Exception {
        //state 0收藏 1点赞 2评论 3分享
        Integer fabulous = 0;
        MyParticipate myParticipate = new MyParticipate();
        myParticipate.setAddTime(sdf.format(System.currentTimeMillis()));
        myParticipate.setUserId(userId);
        myParticipate.setState(state);
        myParticipate.setArticleId(id);
        myParticipate.setCategory(category);
        myParticipate.setParticipateId(UuidUtils.getUUID());
        if (state.equals("3")){
            Integer fenxaing = myParticipateMapper.fenxaing(id);
            if (fenxaing==0){
                try {
                    myParticipateMapper.insert(myParticipate);
                } catch (Exception e) {
                    throw new Exception("添加到我的参与失败");
                }
            }
        }else{
            try {
                myParticipateMapper.insert(myParticipate);
            } catch (Exception e) {
                throw new Exception("添加到我的参与失败");
            }
            //查询该用户的 该篇文章 是否为第一次 点赞 评论 收藏
            Integer integer = centerMapper.centerCount(id, userId);
            if (integer == 0) {
                try {
                    insert(userId,id,state);
                } catch (Exception e) {
                    throw new Exception("添加center失败");
                }
            }else if (integer == 1){
                try {
                    update(userId,id,state);
                } catch (Exception e) {
                    throw new Exception("修改center失败");
                }
            }
            if (state.equals("0")) {
                try {
                    fabulous = fineArtMapper.addCollection(id);
                } catch (Exception e) {
                    throw new Exception("收藏失败");
                }

            } else if (state.equals("1")) {
                try {
                    fabulous = fineArtMapper.fabulous(id);
                } catch (Exception e) {
                    throw new Exception("点赞失败");
                }
            }
        }

        return fabulous;
    }

    @Override
    public Integer reduceZan(String id, String userId, String category, String state) throws Exception {
        Integer reduceZan = 0;
        MyParticipate myParticipate = new MyParticipate();
        myParticipate.setState(state);
        myParticipate.setArticleId(id);
        myParticipate.setUserId(userId);
        myParticipate.setCategory(category);
        int delete;
        try {
            delete = myParticipateMapper.delete(myParticipate);
        } catch (Exception e) {
            throw new Exception("我的参与删除失败");
        }

        try {
            cancel(userId, id, state);
        } catch (Exception e) {
            throw new Exception("修改取消 center失败");
        }

        if (state.equals("0")) {
            try {
                reduceZan = fineArtMapper.deleteCollection(id);
            } catch (Exception e) {
                throw new Exception("取消收藏失败");
            }
        } else if (state.equals("1")) {
            try {
                reduceZan = fineArtMapper.reduceZan(id);
            } catch (Exception e) {
                throw new Exception("取消点赞失败");
            }
        }
        return reduceZan + delete;
    }

    @Override
    public List<FineArt> recommendArticle(String designStyle, String designPlace) throws Exception {
        List<FineArtNew> designArticles;
        try {
           // designArticles = fineArtMapper.recommendArticle();
        } catch (Exception e) {
            throw new Exception("获取失败");
        }
        return null;
    }

    @Override
    public Map<String, Object> specific(String designId, String userId,String state) throws Exception {
        //state 类别0 :用户发出的
        // 1:系统发出的
        Map<String,Object> map = new HashMap<>();
        FineArtNew specific;
        try {
            if (state.equals("1")){
                specific = fineArtMapper.specific(designId, userId);
                map.put("specific",specific);
            }else if (state.equals("0")){
                specific = fineArtMapper.specific(designId, userId);
                String[] split = specific.getProductId().split(",");
                List<Product> list = new ArrayList<>();
                for (String s : split) {
                    Product all = productMapper.all(s);
                    list.add(all);
                }
                map.put("shop",list);
                map.put("specific",specific);
            }

        } catch (Exception e) {
            throw new Exception("获取内容失败");
        }
        List<FineArtNew> designArticles;
        try {
            designArticles = fineArtMapper.recommendArticle(userId,designId);
            map.put("fineArticles",designArticles);
        } catch (Exception e) {
            throw new Exception("获取失败");
        }

        return map;
    }

    @Override
    public  Map<String,Object> myAddFine(String userId,int page,int count) throws Exception {
        List<FineArtNew> fineArts;
        Map<String,Object> map = new HashMap<>();
        try {
            FineArt fineArt = new FineArt();
            fineArt.setUserId(userId);
            int integer = fineArtMapper.selectCount(fineArt);
            fineArts = fineArtMapper.myAddFine(userId,page*count-count,count);
            map.put("list",fineArts);
            if (page * count <= integer) {
                map.put("hasMore", 1);
            } else {
                map.put("hasMore", 0);
            }
        } catch (Exception e) {
            throw new Exception("获取失败");
        }

        return map;
    }

    @Override
    public Map<String,Object> myDraft(String userId,int page,int count) throws Exception {
        List<Caogao> caogaos;
        try {
            caogaos = fineArtMapper.myDraft(userId,page*count-count,count);
            for (Caogao caogao : caogaos) {
                caogao.setDay(timeUtil.day(caogao.getAddTime().substring(0, 10)) + 30);
            }
        } catch (Exception e) {
            throw new Exception("获取失败");
        }
        Integer integer = fineArtMapper.caoGaoNum();
        Map<String,Object> map = new HashMap<>();
        map.put("list",caogaos);
        if (page * count <= integer) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }

    @Override
    public  Map<String,Object> bianji(String id) throws Exception {
        //state 类别0 :用户发出的
        // 1:系统发出的
        Map<String,Object> map = new HashMap<>();
        FineArt specific;
        try {
                FineArt fineArt = new FineArt();
                fineArt.setFineId(id);
                specific = fineArtMapper.selectOne(fineArt);
                String[] split = specific.getProductId().split(",");
                if (!split[0].isEmpty()){
                    List<Product> list = new ArrayList<>();
                    for (String s : split) {
                        Product all = productMapper.all(s);
                        list.add(all);
                    }
                    map.put("shop",list);
                }
            map.put("specific",specific);

        } catch (Exception e) {
            throw new Exception("获取内容失败");
        }

        return map;
    }

    @Override
    public Integer delete(String id,String state) throws Exception {
        if (state.equals("0")){
            //根据文章id找到评论id  放到list
            List<CommentId> commentIds = commentMapper.commentAll(id);
            for (CommentId commentId : commentIds) {
                try {
                    commentMapper.deleteComment(commentId.getCommentId());
                } catch (Exception e) {
                    throw new Exception("删除评论失败");
                }
                try {
                    commentRelationMapper.deleteCommentRelation(commentId.getCommentId());
                } catch (Exception e) {
                    throw new Exception("删除comment_relation失败");
                }
                try {
                    commentMapper.deleteCommentReply(commentId.getCommentId());
                } catch (Exception e) {
                    throw new Exception("删除评论回复失败");
                }
            }
            try {
                centerMapper.deleteCenter(id);
            } catch (Exception e) {
                throw new Exception("删除center失败！");
            }
            try {
                myParticipateMapper.deleteArticle(id);
            } catch (Exception e) {
                throw new Exception("从我的参与中删除失败");
            }
        }

        try {
        fineArtMapper.deleteArticle(id);

        } catch (Exception e) {
            throw new Exception("删除文章失败");
        }

        return null;
    }

    @Override
    public Integer update(String fineId,String fineTitle, String fineContent, String draft, String fineImage, String list,String userId,String shopId) {
        List<String> list1 = new ArrayList<>();
        if (!list.isEmpty()){
            List<Product> products = JSONArray.parseArray(list, Product.class);
            for (Product value : products) {
                Product product = new Product();
                String uuid = UuidUtils.getUUID();
                product.setProductId(uuid);
                product.setImageId(value.getImageId());
                product.setProductContent(value.getProductContent());
                product.setShopContent(value.getShopContent());
                product.setShopImage(value.getShopImage());
                product.setShopPrice(value.getShopPrice());
                product.setShopLink(value.getShopLink());
                list1.add(uuid);
                productMapper.insert(product);
            }
        }
        if (!shopId.isEmpty()){
            String[] split = shopId.split(",");
            for (String s : split) {
                productMapper.deleteId(s);
            }
        }

        return fineArtMapper.upodateOne(fineId,fineImage,StringUtils.join(list1, ","),fineContent,draft,fineTitle,sdf.format(System.currentTimeMillis()),sdf.format(System.currentTimeMillis()));
    }

    @Override
    public Integer userCount(String id, String state) {
        switch (state) {
            case "1":
                designArticleMapper.userCount(id);
                break;
            case "2":
                softProductMapper.userCount(id);
                break;
            case "3":
                fineArtMapper.userCount(id);
                break;
        }
        return 1;

    }

    //0收藏 1点赞 2评论 3分享 b
    private void insert(String userId, String id, String state) {
        Center center = new Center();
        center.setArticleId(id);
        center.setUserId(userId);
        switch (state) {
            case "0":
                center.setCollection("0");
                center.setZan("1");
                center.setDiscuss("1");
                break;
            case "1":
                center.setZan("0");
                center.setDiscuss("1");
                center.setCollection("1");
                break;
            case "2":
                center.setDiscuss("0");
                center.setZan("1");
                center.setCollection("1");
                break;
        }

        centerMapper.insert(center);
    }
    //0收藏 1点赞 2评论 3分享
    private void update(String userId, String id, String state) {
        centerMapper.update(userId, id, state);
    }
    //  取消  0收藏 1点赞 2评论 3分享
    private void cancel(String userId, String id, String state){
        centerMapper.cancel(userId, id, state);
    }
}
